<template>
  <a-card :bordered="false">
  <!--<div>
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-radio-group :default-value="7" v-model="queryParam.day" button-style="solid" @change="searchQuery" :style="{ marginBottom: '8px' }">
              <a-radio-button :value="7">七天有效</a-radio-button>
              <a-radio-button :value="2">2天(48小时)有效</a-radio-button>
            </a-radio-group>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <div>
      <a-table
        ref="table"
        size="middle"
        rowKey="id"
        class="j-table-force-nowrap"
        :scroll="{x:true}"
        :columns="columns"
        :dataSource="dataSource"
        :loading="loading"
        :pagination=false
        :filterMultiple="'false'"
        :defaultExpandAllRows="'true'"
        :expandedRowKeys="expandedRowKeys"
        @change="handleTableChange"
        @expand="handleExpand"
        v-bind="tableProps">
        <span slot="action" slot-scope="text, rowItem">
          <a @click="showPeople(rowItem)" >查看明细</a>
            <a-popconfirm title="确定执行吗?" v-has="'psnType:getNucleicBtn'" @confirm="() => getNucleicByType(rowItem)">
                  <a-divider type="vertical" /><a style="color: #faad14;">同步检测数据</a>
                </a-popconfirm>
        </span>
      </a-table>
    </div>
  </div>
    <wo-people-nuceli-modal ref="peopleListModal"></wo-people-nuceli-modal>
    <a-modal  :width="'90%'" v-model="peopleListModalVisible" title="核酸检测明细" :footer=null>
      <wo-people-nucelic-list ref="pList"></wo-people-nucelic-list>
    </a-modal>-->
  </a-card>
</template>

<script>
  import { getAction, deleteAction } from '@/api/manage'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import { filterObj } from '@/utils/util';
  import WoPeopleNuceliModal from "../people/WoPeopleNuceliModal";
  import WoPeopleNucelicList from "../people/WoPeopleNucelicList";

  export default {
    name: "WoPersonTypeList",
    mixins:[JeecgListMixin],
    components: {
      WoPeopleNuceliModal,
      WoPeopleNucelicList
    },
    data () {
      return {
        description: '核酸检测统计页面',
        peopleListModalVisible:false,
        // 表头
        columns: [
          {
            title:'分组名称',
            align:"left",
            dataIndex: 'typeName'
          },
          {
            title:'总人数',
            align:"center",
            dataIndex: 'allCnt'
          },
          {
            title:'已做核酸人数',
            align:"center",
            dataIndex: 'yCnt'
          },
          {
            title:'已做比例',
            align:"center",
            dataIndex: 'yScale'
          },
          {
            title:'未做核酸人数',
            align:"center",
            dataIndex: 'nCnt'
          },
          {
            title: '操作',
            dataIndex: 'id',
            align:"center",
            fixed:"right",
            width:147,
            scopedSlots: { customRender: 'action' },
          },
        ],
        url: {
          list: "/persontype/woPersonType/rootList",
          childList: "/persontype/woPersonType/childList",
          getChildListBatch: "/persontype/woPersonType/getChildListBatch",
          getNucleicByType:'/people/woPeople/getNucleicByType'
        },
        expandedRowKeys:[],
        hasChildrenField:"hasChild",
        pidField:"pid",
        dictOptions: {},
        queryParam:{
          day:7,
        },
        loadParent: false,
        superFieldList:[],
      }
    },
    created() {
      this.getSuperFieldList();
    },
    computed: {
      tableProps() {
        let _this = this
        return {
          // 列表项是否可选择
          rowSelection: {
            selectedRowKeys: _this.selectedRowKeys,
            onChange: (selectedRowKeys) => _this.selectedRowKeys = selectedRowKeys
          }
        }
      }
    },
    props:{

    },
    methods: {
      getNucleicByType(record){
        this.loading=true;
        getAction(this.url.getNucleicByType+"?typeId="+record.id,{}).then(res=>{
          if(res.success){
            this.$message.info("同步成功");
          }else{
            this.$message.warning(res.message)
          }
        }).finally(()=>{
          this.loading = false
        })
      },
      showPeople(record){
        this.peopleListModalVisible=true;
        this.$nextTick(()=> {
          this.$refs.pList.loadPeople(record,this.queryParam.day);
        })
      },
      selectedNode(){
        let node=null;
        this.$emit("onSelected",node);
      },
      loadData(arg){
        this.loading = true
        let params = this.getQueryParams()
        params.hasQuery = 'true'
        getAction(this.url.list,params).then(res=>{
          if(res.success){
            let result = res.result
            if(result.length>0){
              this.dataSource = this.getDataByResult(res.result)
              return this.loadDataByExpandedRows(this.dataSource)
            }else{
              this.dataSource=[]
            }
          }else{
            this.$message.warning(res.message)
          }
        }).finally(()=>{
          this.loading = false
        })
      },
      // 根据已展开的行查询数据（用于保存后刷新时异步加载子级的数据）
      loadDataByExpandedRows(dataList) {
        if (this.expandedRowKeys.length > 0) {
          return getAction(this.url.getChildListBatch,{ parentIds: this.expandedRowKeys.join(','),day:this.queryParam.day }).then(res=>{
            if (res.success && res.result.length>0) {
              //已展开的数据批量子节点
              let records = res.result
              const listMap = new Map();
              for (let item of records) {
                let pid = item[this.pidField];
                if (this.expandedRowKeys.join(',').includes(pid)) {
                 let mapList = listMap.get(pid);
                  if (mapList == null) {
                    mapList = [];
                  }
                  mapList.push(item);
                  listMap.set(pid, mapList);
                }
              }
              let childrenMap = listMap;
              let fn = (list) => {
                if(list) {
                  list.forEach(data => {
                    if (this.expandedRowKeys.includes(data.id)) {
                      data.children = this.getDataByResult(childrenMap.get(data.id))
                      fn(data.children)
                    }
                  })
                }
              }
              fn(dataList)
            }
          })
        } else {
          return Promise.resolve()
        }
      },
      getQueryParams(arg) {
        //获取查询条件
        let sqp = {}
        let param = {}
        if(this.superQueryParams){
          sqp['superQueryParams']=encodeURI(this.superQueryParams)
          sqp['superQueryMatchType'] = this.superQueryMatchType
        }
        if(arg){
          param = Object.assign(sqp, this.isorter ,this.filters);
        }else{
          param = Object.assign(sqp, this.queryParam, this.isorter ,this.filters);
        }
        if(JSON.stringify(this.queryParam) === "{}" || arg){
          param.hasQuery = 'false'
        }else{
          param.hasQuery = 'true'
        }
        param.field = this.getQueryField();
        return filterObj(param);
      },
      searchReset() {
        //重置
        this.expandedRowKeys = []
        this.queryParam = {}
        this.loadData(1);
      },
      getDataByResult(result){
        if(result){
          return result.map(item=>{
            //判断是否标记了带有子节点
            if(item[this.hasChildrenField]=='1'){
              let loadChild = { id: item.id+'_loadChild', name: 'loading...', isLoading: true }
              item.children = [loadChild]
            }
            return item
          })
        }
      },
      handleExpand(expanded, record){
        // 判断是否是展开状态
        if (expanded) {
          this.expandedRowKeys.push(record.id)
          if (record.children.length>0 && record.children[0].isLoading === true) {
            let params = this.getQueryParams(1);//查询条件
            params[this.pidField] = record.id
            params.hasQuery = 'false'
            params.superQueryParams=""
            params.day=this.queryParam.day;
            getAction(this.url.childList,params).then((res)=>{
              if(res.success){
                if(res.result){
                  record.children = this.getDataByResult(res.result)
                  this.dataSource = [...this.dataSource]
                }else{
                  record.children=''
                  record.hasChildrenField='0'
                }
              }else{
                this.$message.warning(res.message)
              }
            })
          }
        }else{
          let keyIndex = this.expandedRowKeys.indexOf(record.id)
          if(keyIndex>=0){
            this.expandedRowKeys.splice(keyIndex, 1);
          }
        }
      },
      getSuperFieldList(){
        let fieldList=[];
        fieldList.push({type:'string',value:'typeCode',text:'类别编码',dictCode:''})
        fieldList.push({type:'string',value:'typeName',text:'类别名称',dictCode:''})
        fieldList.push({type:'string',value:'pid',text:'父级节点',dictCode:''})
        this.superFieldList = fieldList
      }
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less';
</style>